package com.sxkf.template.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sxkf.core.common.ali.AliPayUtil;
import com.sxkf.core.common.wx.WxPayUtils;
import com.sxkf.core.constant.CommonConstant;
import com.sxkf.template.constants.OrderConstant;
import com.sxkf.template.entity.*;
import com.sxkf.template.mapper.*;
import com.sxkf.template.service.AfterSaleOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxkf.template.service.AmountRecordService;
import com.sxkf.template.service.OrderDetailService;
import com.sxkf.template.utils.OrderUtil;
import org.jeecg.common.exception.SxkfException;
import org.jeecg.common.exception.SxkfExceptionEnum;
import org.jeecg.common.util.CheckEmptyUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 售后订单表 服务实现类
 * </p>
 *
 * @author 杨玉龙
 * @since 2024-12-04 16:21:16
 */
@Service
public class AfterSaleOrderServiceImpl extends ServiceImpl<AfterSaleOrderMapper, AfterSaleOrder> implements AfterSaleOrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private UserCouponMapper userCouponMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private OrderDetailService orderDetailService;
    @Resource
    private StoreMapper storeMapper;
    @Resource
    private ProductSpecMapper productSpecMapper;
    @Resource
    private AmountRecordService amountRecordService;


    @Override
    public void apply(AfterSaleOrder afterSaleOrder) {
        Order order = orderMapper.selectById(afterSaleOrder.getOrderId());

        if (!"12347".contains(order.getState())) {
            throw new SxkfException("该订单状态不可退款");
        }

        afterSaleOrder.setOrderNo(order.getOrderNo());
//        afterSaleOrder.setPrice(order.getPayPrice());
        afterSaleOrder.setPrice(order.getOrderTotalPrice());
        afterSaleOrder.setState("0");
        if (CheckEmptyUtil.isEmpty(afterSaleOrder.getExpectDays())) {
            afterSaleOrder.setExpectDays(3);
        }
//        afterSaleOrder.setPrice(order.getPayPrice());
        save(afterSaleOrder);

        order.setState(OrderConstant.AFTER_SALE);
        orderMapper.updateById(order);
    }

    @Override
    public void pass(String id) {
        AfterSaleOrder afterSaleOrder = getById(id);
        Order order = orderMapper.selectById(afterSaleOrder.getOrderId());

        // 退款操作：退优惠券、还库存、商家扣余额
        handleRefundOrder(order);

        // 退款
        if (order.getPayType().equals("YUE")){
            User user = userMapper.selectById(order.getUserId());
            userMapper.update(null,new LambdaUpdateWrapper<User>()
                    .setSql("amount = amount + " + afterSaleOrder.getPrice())
                    .eq(User::getId,user.getId())
            );
            // 存记录
            AmountRecord amountRecord = new AmountRecord();
            amountRecord.setUserId(user.getId());
            amountRecord.setIsAdd("1");
            amountRecord.setPrice(order.getOrderTotalPrice());
            amountRecord.setRemark("订单退款到余额");
            amountRecordService.save(amountRecord);
        }else if (order.getPayType().equals("WX")){
//            WxPayUtils.refundOrderV3(afterSaleOrder.getOrderNo(), OrderUtil.creatOrder(),order.getPayPrice(),afterSaleOrder.getPrice());
            WxPayUtils.refundOrderV3(afterSaleOrder.getOrderNo(), OrderUtil.creatOrder(),order.getOrderTotalPrice(),afterSaleOrder.getPrice());
        }else if (order.getPayType().equals("ZFB")){
//            AliPayUtil.refund(afterSaleOrder.getOrderNo(),order.getPayPrice().toString());
            AliPayUtil.refund(afterSaleOrder.getOrderNo(),order.getOrderTotalPrice().toString());
        }else {
            throw new SxkfException(SxkfExceptionEnum.PAY_TYPE_ERROR);
        }

//        WxPayUtils.refundOrderV3(afterSaleOrder.getOrderNo(),afterSaleOrder.getId(),order.getPayPrice(),afterSaleOrder.getPrice());

        afterSaleOrder.setState("1");
        updateById(afterSaleOrder);

        order.setState(OrderConstant.REFUND);
        orderMapper.updateById(order);
    }

    @Override
    public void reject(String id, String reason) {
        AfterSaleOrder afterSaleOrder = getById(id);

        Order order = orderMapper.selectById(afterSaleOrder.getOrderId());
        //修改订单状态
        order.setState(OrderConstant.REJECT);
//        //返还优惠券
//        if (CheckEmptyUtil.isNotEmpty(order.getUserCouponId())){
//            userCouponMapper.update(null,new LambdaUpdateWrapper<UserCoupon>()
//                    .set(UserCoupon::getState, CommonConstant.ENABLE)
//                    .eq(UserCoupon::getId,order.getUserCouponId()));
//        }
        orderMapper.updateById(order);

        afterSaleOrder.setState("2");
        afterSaleOrder.setRemark(reason);
        updateById(afterSaleOrder);
    }


    private void handleRefundOrder(Order order) {
//        //如果使用优惠券则退回
//        if (Objects.equals(OrderConstant.NO, order.getState()) && !order.getUserCouponId().equals("0")){
//            UserCoupon userCoupon = userCouponMapper.selectById(order.getUserCouponId());
//            userCoupon.setState(CommonConstant.ENABLE);
//            userCouponMapper.updateById(userCoupon);
//        }
        //返还优惠券
        if (CheckEmptyUtil.isNotEmpty(order.getUserCouponId())){
            UserCoupon userCoupon = userCouponMapper.selectById(order.getUserCouponId());
            // 可用状态判断
            String state =  DateUtil.compare(new Date(),userCoupon.getCloseTime()) < 0 ? CommonConstant.ENABLE: CommonConstant.EXPIRE;
            userCouponMapper.update(null,new LambdaUpdateWrapper<UserCoupon>()
                    .set(UserCoupon::getState, state)
                    .eq(UserCoupon::getId,order.getUserCouponId()));
        }

        //返还商品库存
        List<OrderDetail> orderDetails = orderDetailService.list(new LambdaQueryWrapper<OrderDetail>()
//                .select(OrderDetail::getProductSpecId)
                .eq(OrderDetail::getOrderId, order.getId()));
        orderDetails.forEach(item->{
            ProductSpec productSpec = productSpecMapper.selectById(item.getProductSpecId());
            productSpec.setStock(productSpec.getStock()+item.getProductCount());
            productSpecMapper.updateById(productSpec);
        });

        // 商家扣余额
        storeMapper.update(null,new LambdaUpdateWrapper<Store>()
                .setSql("amount = amount -" + order.getOrderTotalPrice())
                .eq(Store::getId, order.getStoreId())
        );
    }


}
